import requests
import json

class send_weixin:
    def GetToken(self):
        Corpid = 'ww1f51905c4ace368a'  # 企业ID
        CorpSecret = 'ZPmciJs11LOGbjnfIpuceb-8dODXSYHfRpjWfDA5KQE'  # 企业号应用的Secret值
        gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + Corpid + '&corpsecret=' + CorpSecret
        print(gettoken_url)
        try:
            token_file = requests.get(gettoken_url)
        except Exception as e:
            print(e)
        token_data = token_file.text
        print(token_data)
        token_json = json.loads(token_data)
        token_json.keys()
        token = token_json['access_token']
        print(token)
        return token

    def Send_Message(self, Token, Tag, Subject, Content, wechat_name):
        post_data = {
            'touser': wechat_name,  # 通讯录用户ID
            # 'toparty': '1',  # 通讯录组ID
            'totag': Tag,  # 通讯录标签ID
            'msgtype': 'text',
            'agentid': 1000002,  # 企业号应用的agentid
            'text': {
                'content': Subject + '\n' + Content
            },
            'safe': 0
        }

        post_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + Token
        print(post_url)
        try:
            r = requests.post(post_url, data=json.dumps(post_data))

        except Exception as e:
            print(e)
    def run(self, wechat_name,equipment_name):
        Corpid = 'ww1f51905c4ace368a'
        CorpSecret = 'ZPmciJs11LOGbjnfIpuceb-8dODXSYHfRpjWfDA5KQE'
        Tag = '1'
        Subject = 'owd雷电报警'
        Content = equipment_name
        print(wechat_name)
        Token = self.GetToken()
        self.Send_Message(Token, Tag, Subject, Content, wechat_name)
